package com.bike.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bike.entity.HhAgent;
import com.bike.entity.HhBankBranch;
import com.bike.entity.HhBusiness;
import com.bike.entity.HhBusinessRecord;
import com.bike.entity.HhBusinessUser;
import com.bike.entity.HhCity;
import com.bike.entity.HhWithdraw;
import com.bike.mapper.HhAgentMapper;
import com.bike.mapper.HhBankBranchMapper;
import com.bike.mapper.HhBusinessMapper;
import com.bike.mapper.HhBusinessParentMapper;
import com.bike.mapper.HhBusinessRecordMapper;
import com.bike.mapper.HhBusinessUserMapper;
import com.bike.mapper.HhCityMapper;
import com.bike.mapper.HhFoodMenuMapper;
import com.bike.mapper.HhWithdrawMapper;
import com.bike.util.Constant;
import com.bike.util.Md5Util;
import com.bike.util.PageData;
import com.bike.util.TimeManager;
import com.bike.util.TransFerUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

@Service
public class HhBusinessServiceImpl extends BaseServcieImpl  {

	@Autowired
	HhBusinessMapper hhBusinessMapper;
	@Autowired
	HhCityMapper cityMapper;
	@Autowired
	HhBankBranchMapper bankBranchMapper;
	@Autowired
	HhFoodMenuMapper hhFoodMenuMapper;
	@Autowired
	HhBusinessUserMapper hhBusinessUserMapper;
	@Autowired
	HhBusinessRecordMapper hhBusinessRecordMapper;
	@Autowired
	HhAgentMapper hhAgentMapper;
	@Autowired
	HhWithdrawMapper hhWithdrawMapper;
	@Autowired
	HhAgentServiceImpl hhAgentServiceImpl;
	@Autowired
	HhBusinessParentMapper hhBusinessParentMapper;
	@Autowired
	HhPayRecordServiceImpl hhPayRecordServiceImpl;
	/**
	* 保存
	*/
	public void saveOrUpdate(PageData pd, HhBusiness record) {
		
		Long cityparentid=pd.getLong("cityparentid");
		HhCity city=cityMapper.selectByPrimaryKey(cityparentid);
		if(city!=null){
			if(city.getLevel()==1){
				record.setProvince(city.getTitle());
			}
			if(city.getLevel()==2){
				record.setProvince(city.getParentName());
				record.setCity(city.getTitle());
			}
			if(city.getLevel()==3){
				record.setProvince(city.getRootName());
				record.setCity(city.getParentName());
				record.setCounty(city.getTitle());
			}
			record.setCountyId(cityparentid);
		}
		
		String bankBranchId=pd.getString("bankBranchId");
		HhBankBranch bankBranch=bankBranchMapper.selectByPrimaryKey(bankBranchId);
		if(bankBranch==null){
			bankBranch=new HhBankBranch();
			record.setBankBranchId(null);
		} 
		record.setBankBranch(bankBranch.getBranchName());
		record.setBank(bankBranch.getParentName());
		record.setBankProvince(bankBranch.getProvince());
		record.setBankProvinceId(bankBranch.getProvinceId());
		record.setBankCity(bankBranch.getCity());
		record.setBankCityId(bankBranch.getCityId());
		record.setBankId(bankBranch.getParentId());
		if(pd.getLong("businessId")>0){
			 //编辑
			hhBusinessMapper.updateByPrimaryKeySelective(record);
		}else{
			record.setAddTime(TimeManager.currentTime());
			hhBusinessMapper.insertSelective(record);
		}
	}
	
	/**
	* 删除
	*/
	public int deleteHhBusinessById(long businessId) {
		HhBusiness  ss=new HhBusiness();
		ss.setBusinessId(businessId);
		ss.setStatus(1);
		
		return hhBusinessMapper.updateByPrimaryKeySelective(ss);
	}
	
	/**
	*列表分页
	*/
	public PageData selectHhBusinessList(PageData pd) {
		PageData result=new PageData();
		PageBounds pageBounds=(PageBounds) pd.get("pageB");
		String advanceFilter=pd.getString("advanceFilter");
		if(advanceFilter!=null&&!advanceFilter.equals("")){
			advanceFilter=advanceFilter.replaceAll("'", "");
			JSONArray array=JSONObject.parseArray(advanceFilter);
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<array.size();i++){
				JSONObject object=array.getJSONObject(i);
				String field=object.getString("field");
				String op=object.getString("op");//equal  contains  notequal  greater  greaterorequal  less  lessorequal  beginwith  endwith
				String value=object.getString("value");
				buffer.append(" and ").append(TransFerUtil.getMybatisField(field)).append(TransFerUtil.getMybatisOperation(op,value));
			}
			if(array.size()>0){
				pd.put("condition", buffer.toString());
			}
		}
		List<HhBusiness> records= hhBusinessMapper.selectByPage(pd,pageBounds);
		result.put("rows",records );
		result.put("total", ((PageList<HhBusiness>) records).getPaginator().getTotalCount());
		return result;
	}
	 
	/**
	*列表(全部)
	*/
	public List<HhBusiness> listAll(PageData pd) {
		return  hhBusinessMapper.selectAll(pd);
	}
	
	/**
	* 通过id获取数据
	*/
	public HhBusiness selectByHhBusinessId(Long businessId) {
		HhBusiness business=hhBusinessMapper.selectByPrimaryKey(businessId);
		if(business.getParentId()>0){
			business.setParentName(hhBusinessParentMapper.selectByPrimaryKey(business.getParentId()).getName());
		}
		
		String bankBranchId=business.getBankBranchId();
		if(!StringUtils.isEmpty(bankBranchId)){
			HhBankBranch bankBranch=bankBranchMapper.selectByPrimaryKey(bankBranchId);
			business.setBankProvince(bankBranch.getProvince());
			business.setBankProvinceId(bankBranch.getProvinceId());
			business.setBankCity(bankBranch.getCity());
			business.setBankCityId(bankBranch.getCityId());
			business.setBankId(bankBranch.getParentId());
		}
		return business;
	}

	public PageData selectShopMenus(Long businessId) {
		//HhBusiness business=hhBusinessMapper.selectByPrimaryKey(businessId);
		PageData pData=new PageData();
		if(businessId<=0){
			pData.put("shopMenus",new ArrayList<>());
		}else{
			pData.put("shopMenus",hhFoodMenuMapper.selectFoodMenus(businessId));
		}
		  return pData;
	}

	public int insertRegNewBusiness(PageData pd) {
		
		String businessName=pd.getString("businessName");
		String province=pd.getString("province");
		String city=pd.getString("city");
		String county=pd.getString("county");
		Long countyId=pd.getLong("countyId");
		String contractUser=pd.getString("contractUser");//联系人
		String pwd=pd.getString("pwd");//密码
		String phone=pd.getString("phone");//手机号
		
		HhBusiness business=new HhBusiness();
		business.setAddTime(TimeManager.currentTime());
		business.setPhone(phone);
		business.setProvince(province);
		business.setCity(city);
		business.setCounty(county);
		business.setCountyId(countyId);
		business.setName(businessName);
		hhBusinessMapper.insertSelective(business);
		
		HhBusinessUser businessUser=new HhBusinessUser();
		businessUser.setAddTime(TimeManager.currentTime());
		businessUser.setBusinessId(business.getBusinessId());
		businessUser.setBusinessName(businessName);
		businessUser.setName(contractUser);
		businessUser.setPhone(phone);
		if(pwd.equals("")){
			pwd="123456";
		}
		businessUser.setRole(Constant.boss);
		businessUser.setPwd(Md5Util.MD5(pwd));
		
		return hhBusinessUserMapper.insertSelective(businessUser);
		
	}

	public void updateBusiness(PageData pd, HhBusiness business) {
		hhBusinessMapper.updateByPrimaryKeySelective(business);
	}

	public int updateBusinessWithdraw(HhBusinessUser businessUser) {
		 HhBusiness business=hhBusinessMapper.selectByPrimaryKey(businessUser.getBusinessId());
		 if(business!=null){
			 BigDecimal serviceFee=null;
			BigDecimal businessBalance=business.getBalance();
			BigDecimal trueAccount=business.getBalance();
			if(business.getPayWithdraw()==0){
				serviceFee=businessBalance.multiply(new BigDecimal(Constant.WXwithdrawFee)).setScale(2, RoundingMode.HALF_UP);
				if(serviceFee.doubleValue()==0){
					serviceFee=new BigDecimal("0.01");
				}
				trueAccount=businessBalance.subtract(serviceFee).subtract(new BigDecimal("2"));
			}
			if(trueAccount.doubleValue()<0){
				return 0;
			}
			//余额清零
			business.setBalance(new BigDecimal("0"));
			hhBusinessMapper.updateBalance(business);
			int time=TimeManager.currentTime();
			//增加提现记录
			HhWithdraw hhWithdraw=new HhWithdraw();
			hhWithdraw.setAddTime(time);
			hhWithdraw.setAmount(trueAccount);
			hhWithdraw.setBank(business.getBank());
			hhWithdraw.setBankBranch(business.getBankBranch());
			hhWithdraw.setBankCode(business.getBankCode());
			hhWithdraw.setBankUser(business.getBankName());
			hhWithdraw.setBusinessId(business.getBusinessId());
			hhWithdraw.setBusinessName(business.getName());
			hhWithdraw.setUserBusinessName(businessUser.getName());
			hhWithdraw.setServiceAmount(serviceFee);
			hhWithdraw.setPoundage(new BigDecimal("2"));
			hhWithdraw.setWithdrawAmount(businessBalance);
			hhWithdraw.setType(0);
			hhWithdrawMapper.insertSelective(hhWithdraw);
			
			HhAgent agent= hhAgentServiceImpl.insertOrSelectByPrimaryKey();
			//提现金额
			 HhBusinessRecord businessRecord=new HhBusinessRecord();
			 businessRecord.setAddTime(time);
			 businessRecord.setAmount(trueAccount.toString());
			 businessRecord.setChannel(Constant.withdrawRecord);
			 businessRecord.setFromId(business.getBusinessId());
			 businessRecord.setFromName(business.getName());
			 businessRecord.setToId(agent.getAgentId());
			 businessRecord.setToName(agent.getName());
			 businessRecord.setBusinessId(business.getBusinessId());
			 businessRecord.setBusinessName(business.getName());
			 businessRecord.setStatus(0);//提现进行中 
			 businessRecord.setWithdrawId(hhWithdraw.getWithdrawId());
			 hhBusinessRecordMapper.insertSelective(businessRecord);
			 hhPayRecordServiceImpl.insertAgentPayRecord(agent, trueAccount, Constant.platform, "用户提现金额",true);
			//提现手续费
			 if(serviceFee!=null){
				 HhBusinessRecord businessRecordWith=new HhBusinessRecord();
				 businessRecordWith.setAddTime(time);
				 businessRecordWith.setAmount(serviceFee.toString());
				 businessRecordWith.setChannel(Constant.withdrawServiceFee);
				 businessRecordWith.setFromId(business.getBusinessId());
				 businessRecordWith.setFromName(business.getName());
				 businessRecordWith.setToId(agent.getAgentId());
				 businessRecordWith.setToName(agent.getName());
				 businessRecordWith.setBusinessId(business.getBusinessId());
				 businessRecordWith.setBusinessName(business.getName());
				 businessRecordWith.setWithdrawId(hhWithdraw.getWithdrawId());
				 hhBusinessRecordMapper.insertSelective(businessRecordWith);
				 hhPayRecordServiceImpl.insertAgentPayRecord(agent, serviceFee, Constant.platform, "用户提现手续费",true);
			 }
			 //银联转账手续费
			 HhBusinessRecord businessRecordWith=new HhBusinessRecord();
			 businessRecordWith.setAddTime(time);
			 businessRecordWith.setAmount("2");
			 businessRecordWith.setChannel(Constant.withdrawBankFee);
			 businessRecordWith.setFromId(business.getBusinessId());
			 businessRecordWith.setFromName(business.getName());
			 businessRecordWith.setToId(agent.getAgentId());
			 businessRecordWith.setToName(agent.getName());
			 businessRecordWith.setBusinessId(business.getBusinessId());
			 businessRecordWith.setBusinessName(business.getName());
			 businessRecordWith.setWithdrawId(hhWithdraw.getWithdrawId());
			 hhBusinessRecordMapper.insertSelective(businessRecordWith);
			 
			//更新系统平台代理商余额  加入，提现完成 在减掉
			agent.setBalance(agent.getBalance().add(businessBalance ));
			hhPayRecordServiceImpl.insertAgentPayRecord(agent, new BigDecimal("2"), Constant.platform, "用户提现银行转账手续费",true);
			 hhAgentMapper.updateByPrimaryKeySelective(agent);
			 return 1;
		 }
		return 0;
	}

	public List<HhBusiness> selectAllByParentId(Long parentBusinessId) {
		PageData pd=new PageData();
		pd.put("parentId", parentBusinessId);
		return hhBusinessMapper.selectAll(pd);
	}
}

